package com.zdc.encrypt;

import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author zdc
 * @description
 * @date 2025/8/14 9:57
 */
public class ConfigEncryptor {
    private static final String ALGORITHM = "PBEWithMD5AndDES";

    private static final String _PASSWORD_ = "1234abcdABCD";

    // 加密并压缩配置
    public static byte[] encryptAndCompressConfig(String configContent, String password) throws IOException {
        if (password == null || password.trim().length() <= 0) {
            throw new RuntimeException("非法密码！");
        }
        // 加密
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        encryptor.setAlgorithm(ALGORITHM);
        encryptor.setPassword(password);
        String encrypted = encryptor.encrypt(configContent);
        // 压缩
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(out)) {
            gzOut.write(encrypted.getBytes());
        }
        return out.toByteArray();
    }

    // 解压并解密配置
    public static String decompressAndDecryptConfig(byte[] compressedData, String password) throws IOException {
        if (password == null || password.trim().length() <= 0) {
            throw new RuntimeException("非法密码！");
        }
        // 解压
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (ByteArrayInputStream in = new ByteArrayInputStream(compressedData);
             GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = gzIn.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        }
        String encrypted = out.toString();
        // 解密
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        encryptor.setAlgorithm(ALGORITHM);
        encryptor.setPassword(password);
        return encryptor.decrypt(encrypted);
    }
}